package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.excel;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.excel.ExcelTemplatesBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysFiles;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.TExcelTemplates;
import com.xiaoxu.intranetweb.util.PermissionCheck;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.WebFunctionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@RestController
@RequestMapping(value = "/excelTemplates")
public class ExcelTemplatesController {
    @Autowired
    private ExcelTemplatesBu excelTemplatesBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private WebFunctionUtil webFunctionUtil;

    //    获取所有模板
    @GetMapping("/getAllExcelTemplates")
    public SzResult getAllExcelTemplates(@RequestParam(value = "functionName", required = false) String functionName, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return excelTemplatesBu.getAllTemplates(token, functionName, plantId);
    }

    //修改模板
    @PostMapping("/updateExcelTemplates")
    public SzResult updateExcelTemplates(@RequestBody JSONObject jsonParam, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String id = jsonParam.getString("id");
//        修改名称
        String excelFunctionName = jsonParam.getString("excelFunctionName");
        String plantId = request.getHeader("Plant-Id");
//        修改备注
        String excelRemark = jsonParam.getString("excelRemark");

        Map userPermissionWeb = userInfoDao.getUserPermissionWeb(StpUtil.getLoginIdByToken(token).toString());

        Map permission = webFunctionUtil.webFunction(userPermissionWeb, "manageExcelTemplates");
        if (permission.get("code").equals(0)) {
            return SzResult.error(permission.get("msg").toString());
        }
        return excelTemplatesBu.updateExcelTemplates(id, excelFunctionName, excelRemark, token, plantId);
    }

    //    下载excel模板文件接口
    @GetMapping("/download")
    public void downloadFile(@RequestParam("fileId") String fileId, HttpServletResponse response, HttpServletRequest request) throws IOException {
        try {
            TExcelTemplates tExcelTemplates = excelTemplatesBu.downloadExcelTemplates(fileId);
            Path path = Paths.get(tExcelTemplates.getExcelPath() + File.separator + tExcelTemplates.getId() + "." + "xlsx");
            String fileName = tExcelTemplates.getExcelFunctionName() + "." + "xlsx";
            InputStream inputStream = new BufferedInputStream(Files.newInputStream(new File(path.toString()).toPath()));
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/x-download");
            response.setHeader("Content-Length", "" + path.toFile().length());
            response.setHeader("Content-Disposition", "attachment; filename*=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            response.setStatus(500);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            e.printStackTrace();
        }
    }

    //上传新模板
    @PostMapping("/upload")
    public SzResult uploadExcelTemplates(@RequestParam("file") MultipartFile file,
                                         @RequestParam(required = false) String connId,
                                         HttpServletRequest request) throws Exception {

//        如果文件不是.xlsx格式直接返回
        if (!file.getOriginalFilename().endsWith(".xlsx")) {
            return SzResult.error("文件格式错误,请上传.xlsx格式文件");
        }
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");

        Map userPermissionWeb = userInfoDao.getUserPermissionWeb(StpUtil.getLoginIdByToken(token).toString());

        Map permission = webFunctionUtil.webFunction(userPermissionWeb, "manageExcelTemplates");
        if (   permission.get("code").equals(0)) {
            return SzResult.error(permission.get("msg").toString());
        }
        return excelTemplatesBu.uploadExcelTemplates(file, connId, token, plantId);
    }

    //    新建模板
    @PostMapping("/createExcelTemplates")
    @PermissionCheck("manageExcelTemplates")
    public SzResult createExcelTemplates(@RequestBody JSONObject jsonParam, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String excelFunction = jsonParam.getString("excelFunction");
        String excelFunctionFiled = jsonParam.getString("excelFunctionFiled");
        String excelFunctionName = jsonParam.getString("excelFunctionName");
        String excelRemark = jsonParam.getString("excelRemark");
        String plantId = request.getHeader("Plant-Id");
        return excelTemplatesBu.createExcelTemplates(excelFunction, excelFunctionName, excelFunctionFiled, excelRemark, token, plantId);
    }
}
